//
//  HistoryNotificationViewController.m
//  leo
//
//  Created by 张旭 on 15/10/2.
//  Copyright (c) 2015年 mdx. All rights reserved.
//

#import "HistoryNotificationViewController.h"
#import "DataManager.h"
#import "LeoMsg.h"
#import "SyncManager.h"
@interface HistoryNotificationViewController ()
@property(nonatomic,strong) NSArray *messageList;
@property(nonatomic,strong) DataManager *dataManager;
@property(nonatomic,strong) Watch *selectWatch;
@property(nonatomic,strong) User *user;
@end

@implementation HistoryNotificationViewController
@synthesize historyItemNoButtonTableViewCell;
@synthesize historyItemWithButtonTableViewCell;

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:BINDCONFIRMFINISHED object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NEWHISTORYNOTIFICATION object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:VICEADMINBINDDEVICE object:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.extendedLayoutIncludesOpaqueBars = YES;
    self.title=@"历史通知";
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:BINDCONFIRMFINISHED object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:NEWHISTORYNOTIFICATION object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:VICEADMINBINDDEVICE object:nil];
    // Do any additional setup after loading the view from its nib.
    self.dataManager=[[DataManager alloc] init];
    if(self.dataManager==NULL)
    {
        [LeoMsg showMsg:@"程序发生错误，code is 24"];
        return;
    }
    self.user=[User sharedSingleton];
    if(self.user==NULL)
    {
        [LeoMsg showMsg:@"程序发生错误，code is 25"];
        return;
    }
    self.selectWatch=[self.dataManager getActiveWatch:self.user.uid];
    if(self.selectWatch==NULL)
    {
        [LeoMsg showMsg:@"没有选中手表，code is 2"];
        return;
    }
    dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    if(queue!=NULL)
    {
        dispatch_async(queue, ^{
            SyncManager *syncManager=[[SyncManager alloc] init];
            if(syncManager!=NULL)
            {
                [syncManager getGeoFences:self.selectWatch.deviceUid completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                    if(result==SUCESS)
                    {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self initData];
                            [self.tableView reloadData];
                        });
                    }
                }];
            }
        });

    }
    [self initData];
    [self worktable];
}
-(void)initData
{
    if(self.dataManager==NULL)
    {
        NSLog(@"%@,initData,dataManager is null.",history_tag);
    }
    self.messageList=[self.dataManager getMessageList:self.user.uid deviceUid:self.selectWatch.deviceUid];
}

-(void)worktable{
    self.automaticallyAdjustsScrollViewInsets=NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    
    UINib *cellNotiNoButton = [UINib nibWithNibName:@"HistoryItemNoButtonTableViewCell" bundle:nil];
    [self.tableView registerNib:cellNotiNoButton forCellReuseIdentifier:@"historyitemnobuttontableviewcell"];
    self.historyItemNoButtonTableViewCell  = [self.tableView dequeueReusableCellWithIdentifier:@"historyitemnobuttontableviewcell"];
    
    UINib *cellNotiWithButton = [UINib nibWithNibName:@"HistoryItemWithButtonTableViewCell" bundle:nil];
    [self.tableView registerNib:cellNotiWithButton forCellReuseIdentifier:@"historyitemwithbuttontableviewcell"];
    self.historyItemWithButtonTableViewCell  = [self.tableView dequeueReusableCellWithIdentifier:@"historyitemwithbuttontableviewcell"];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.view.window==nil)
    {
        self.view=nil;
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    int row=(int)[indexPath row];
    PMessage *message=[self.messageList objectAtIndex:row];
    if(message==NULL)
        return 79;
    if(message.type==PT_VICE_BOUND_REQUEST&&message.commentValue==0)
    {
        return 102;
    }
    else
    {
        return 79;
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.messageList.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    int row=(int)[indexPath row];
    PMessage *message=[self.messageList objectAtIndex:row];
    if(message==NULL)
        return NULL;
    if (message.type==PT_VICE_BOUND_REQUEST&&message.commentValue==0) {
        HistoryItemWithButtonTableViewCell *cell = (HistoryItemWithButtonTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"historyitemwithbuttontableviewcell"];
        cell.navController=self.navigationController;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        Watch *theWacth=[self.dataManager getWatch:message.deviceUid];
        NSString *watchName=NULL;
        if(theWacth!=NULL)
            watchName=theWacth.nickname;
        else
            watchName=@"手表";
        NSString *title=[NSString stringWithFormat:@"%@请求称为%@的副管理员\n是否同意？",message.nickName,watchName];
        cell.cellLabel.text=title;
        cell.message=message;
        return cell;
    }
    else
    {
        HistoryItemNoButtonTableViewCell *cell = (HistoryItemNoButtonTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"historyitemnobuttontableviewcell"];
        cell.navController=self.navigationController;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSString *title=NULL;
        Watch *theWacth=[self.dataManager getWatch:message.deviceUid];
        NSString *watchName=NULL;
        if(theWacth!=NULL)
            watchName=theWacth.nickname;
        else
            watchName=@"手表";
        if(message.type==PT_VICE_BOUND_REQUEST)
        {

            if(message.commentValue==1)
            {
                title=[NSString stringWithFormat:@"您拒绝%@成为%@的副管理员",message.nickName,watchName];
            }
            else if(message.commentValue==2)
            {
                title=[NSString stringWithFormat:@"%@成为%@的副管理员",message.nickName,watchName];
            }
            cell.cellImage.image=[UIImage imageNamed:@"history_key2@2x.png.png"];
            cell.timeLabel.text=[NSString stringWithFormat:@"%@",[Tooler getHistoryDateTime:message.genTime]];
        }
        else if(message.type==PT_VICEADMIN_JOIN)
        {
            title=[NSString stringWithFormat:@"%@成为%@的副管理员",message.nickName,watchName];
            cell.cellImage.image=[UIImage imageNamed:@"history_key2@2x.png.png"];
            cell.timeLabel.text=[NSString stringWithFormat:@"%@",[Tooler getHistoryDateTime:message.genTime]];
        }
        else if(message.type==PT_GEOFENCE_IN_OUT)
        {
            cell.cellImage.image=[UIImage imageNamed:@"history_security@2x.png"];
            NSString *fName=NULL;
            Fence *fence=[self.dataManager getFence:message.fid];
            if(fence!=NULL)
            {
                fName=[Tooler getFenceName:fence.type];
                if(fName==NULL||[fName isEqualToString:@"(null)"]||[fName isEqualToString:@""])
                    fName=fence.title;
                if(fName==NULL||[fName isEqualToString:@"(null)"]||[fName isEqualToString:@""])
                    fName=@"其他安全区域";
            }
            else
            {
                fName=@"其他安全区域";
            }
            if(message.fenceType==0)
            {
                title=[NSString stringWithFormat:@"%@进入%@",watchName,fName];
            }
            else if(message.fenceType==1)
            {
                title=[NSString stringWithFormat:@"%@离开%@",watchName,fName];
            }
            if(message.location!=NULL&&message.location.loc!=NULL)
            {
                cell.locLabel.text=[NSString stringWithFormat:@"%@",message.location.loc];
            }
            if(message.location!=NULL&&message.location.gen_time!=NULL)
            {
                cell.timeLabel.text=[NSString stringWithFormat:@"%@",[Tooler getHistoryDateTime:message.location.gen_time]];
            }
        }
        else if(message.type==PT_SOS)
        {
            cell.cellImage.image=[UIImage imageNamed:@"history_sos@2x.png"];
            title=[NSString stringWithFormat:@"%@发起紧急电话",watchName];
            if(message.location!=NULL&&message.location.loc!=NULL)
            {
               cell.locLabel.text=[NSString stringWithFormat:@"%@",message.location.loc];
            }
            if(message.location!=NULL&&message.location.gen_time!=NULL)
            {
                cell.timeLabel.text=[NSString stringWithFormat:@"%@",[Tooler getHistoryDateTime:message.location.gen_time]];
            }
        }
        else if(message.type==PT_LOW_BATTERY)
        {
            cell.cellImage.image=[UIImage imageNamed:@"history_battery5@2x.png"];
            title=[NSString stringWithFormat:@"%@手表电量低于%d%%",watchName,message.battery];
            if(message.location!=NULL&&message.location.loc!=NULL)
            {
               cell.locLabel.text=[NSString stringWithFormat:@"%@",message.location.loc];
            }
            if(message.location!=NULL&&message.location.gen_time!=NULL)
            {
                cell.timeLabel.text=[NSString stringWithFormat:@"%@",[Tooler getHistoryDateTime:message.location.gen_time]];
            }
        }
        else if(message.type==PT_BIRTHDAY_NOTIFY)
        {
            NSString *theName=NULL;
            Manager *manager=[self.dataManager getManagerByUid:message.uid];
            if(manager!=NULL)
            {
                theName=manager.nickName;
            }
            else
            {
                Watch *birthWatch=[self.dataManager getWatch:message.uid];
                if(birthWatch!=NULL)
                {
                    theName=birthWatch.nickname;
                }
            }
            if(theName==NULL)
            {
                theName=@"手表联系人";
            }
           
            title=[NSString stringWithFormat:@"%@是%@的生日",message.specialTime,theName];

        }
        else if(message.type==PT_FESTIVAL_NOTIFY)
        {
            title=[NSString stringWithFormat:@"%@是%@",message.specialTime,message.specialName];
        }
        else if(message.type==PT_WATCH_SIM_CHANGE)
        {
            Watch *simWatch=[self.dataManager getWatch:message.deviceUid];
            if(simWatch!=NULL)
            {
                title=[NSString stringWithFormat:@"%@的sim卡有变更",simWatch.nickname];
            }
            else
            {
                title=@"手表sim卡有变更";
            }
            
        }
        cell.cellLabel.text=title;
        return cell;
    }

}
- (void)receiveNotification:(NSNotification *)sender {
    
    [self initData];
    [self.tableView reloadData];
    
}
@end
